import React, { useState, useRef, useEffect } from 'react';
import { toast } from '../lib/toast-with-audio';
import { useTheme } from '../hooks/useTheme';
import UserDrawer from '../components/UserDrawer';
import { userApi } from '../store/user';
import { useAuth } from '../contexts/authContext';
import type { User } from '../types/user';
import { motion } from 'framer-motion';



// 状态徽章组件
const StatusBadge: React.FC<{ status: number }> = ({ status }) => {
  const statusText = status === 1 ? '启用' : '停用';
  const className = status === 1 
    ? 'bg-green-100 dark:bg-green-900 text-green-700 dark:text-green-300'
    : 'bg-red-100 dark:bg-red-900 text-red-700 dark:text-red-300';
  
  return (
    <span className={`px-2 py-1 text-xs font-medium rounded-full ${className}`}>
      {statusText}
    </span>
  );
};

// 角色徽章组件
const RoleBadge: React.FC<{ role: string }> = ({ role }) => {
  let className = '';
  
  switch (role) {
    case '超级管理员':
      className = 'bg-purple-100 dark:bg-purple-900 text-purple-700 dark:text-purple-300';
      break;
    case '项目经理':
      className = 'bg-blue-100 dark:bg-blue-900 text-blue-700 dark:text-blue-300';
      break;
    case '开发工程师':
      className = 'bg-green-100 dark:bg-green-900 text-green-700 dark:text-green-300';
      break;
    case '测试工程师':
      className = 'bg-yellow-100 dark:bg-yellow-900 text-yellow-700 dark:text-yellow-300';
      break;
    case '产品经理':
      className = 'bg-indigo-100 dark:bg-indigo-900 text-indigo-700 dark:text-indigo-300';
      break;
    default:
      className = 'bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300';
  }
  
  return (
    <span className={`px-2 py-1 text-xs font-medium rounded-full ${className}`}>
      {role}
    </span>
  );
};

// 头像组件
const Avatar: React.FC<{ 
  user: any; 
  onAvatarChange: (userId: number, avatar: string) => void;
  size?: 'sm' | 'md' | 'lg';
}> = ({ user, onAvatarChange, size = 'lg' }) => {
  const fileInputRef = useRef<HTMLInputElement>(null);
  
  const sizeClasses = {
    sm: 'w-8 h-8',
    md: 'w-12 h-12',
    lg: 'w-16 h-16'
  };

  const handleAvatarClick = () => {
    fileInputRef.current?.click();
  };

  const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (file) {
      // 验证文件类型
      if (!file.type.startsWith('image/')) {
        toast.error('请选择图片文件');
        return;
      }
      
      // 验证文件大小（最大5MB）
      if (file.size > 5 * 1024 * 1024) {
        toast.error('图片大小不能超过5MB');
        return;
      }

      const reader = new FileReader();
      reader.onload = (e) => {
        const avatarDataUrl = e.target?.result as string;
        onAvatarChange(user.id, avatarDataUrl);
        toast.success(`${user.name}的头像已更新`);
      };
      reader.readAsDataURL(file);
    }
  };

  const getInitials = (name: string) => {
    // 显示姓氏的第一个字符（中文名字按空格分割）
    const nameParts = name.trim().split(' ');
    if (nameParts.length > 1) {
      // 如果有空格，取第一个部分作为姓氏
      return nameParts[0].slice(0, 1).toUpperCase();
    } else {
      // 如果没有空格，取第一个字符
      return name.slice(0, 1).toUpperCase();
    }
  };

  const getAvatarColor = (name: string) => {
    const colors = [
      'bg-blue-500', 'bg-green-500', 'bg-purple-500', 
      'bg-red-500', 'bg-yellow-500', 'bg-indigo-500'
    ];
    const index = name.charCodeAt(0) % colors.length;
    return colors[index];
  };

  return (
    <div className="relative group">
      {user.avatar ? (
        <img 
          src={user.avatar} 
          alt={user.name}
          className={`${sizeClasses[size]} rounded-full object-cover cursor-pointer border-2 border-gray-200 dark:border-gray-600 group-hover:border-blue-400 transition-colors relative z-10`}
          onClick={handleAvatarClick}
        />
      ) : (
        <div 
          className={`${sizeClasses[size]} ${getAvatarColor(user.name)} rounded-full flex items-center justify-center text-white font-medium cursor-pointer border-2 border-gray-200 dark:border-gray-600 group-hover:border-blue-400 transition-colors relative z-10`}
          onClick={handleAvatarClick}
        >
          {getInitials(user.name)}
        </div>
      )}
      
      {/* 上传图标 */}
      <div className="absolute inset-0 bg-black bg-opacity-0 group-hover:bg-opacity-30 rounded-full flex items-center justify-center transition-all opacity-0 group-hover:opacity-100 pointer-events-none">
        <i className="fa-solid fa-camera text-white text-sm"></i>
      </div>
      
      <input
        ref={fileInputRef}
        type="file"
        accept="image/*"
        className="hidden"
        onChange={handleFileChange}
      />
    </div>
  );
};

export default function Users() {
  const { isDark } = useTheme();
  const { pendingUsers, approveUser, rejectUser } = useAuth();
  const [activeTab, setActiveTab] = useState<'users' | 'pending'>('users');
  const [searchTerm, setSearchTerm] = useState('');
  const [statusFilter, setStatusFilter] = useState('all');
  const [roleFilter, setRoleFilter] = useState('all');
  const [users, setUsers] = useState<User[]>([]);
  const [loading, setLoading] = useState(false);
  
  // 分页相关状态
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [totalUsers, setTotalUsers] = useState(0);
  
  // 抽屉相关状态
  const [drawerOpen, setDrawerOpen] = useState(false);
  const [currentUser, setCurrentUser] = useState<User | null>(null);
  const [drawerMode, setDrawerMode] = useState<'view' | 'edit' | 'create'>('view');

  // 加载用户数据
  useEffect(() => {
    const loadUsers = async () => {
      setLoading(true);
      try {
        const response = await userApi.getUsers({
          page: currentPage,
          pageSize: pageSize,
          search: searchTerm,
          role: roleFilter === 'all' ? undefined : roleFilter,
          status: statusFilter === 'all' ? undefined : (statusFilter === '启用' ? 1 : 0)
        });
        setUsers(response.data);
        setTotalUsers(response.total);
      } catch (error) {
        console.error('加载用户数据失败:', error);
        toast('加载用户数据失败');
      } finally {
        setLoading(false);
      }
    };

    loadUsers();
  }, [currentPage, pageSize, searchTerm, statusFilter, roleFilter]);

  // 分页计算
  const totalPages = Math.ceil(totalUsers / pageSize);
  const startIndex = (currentPage - 1) * pageSize + 1;
  const endIndex = Math.min(currentPage * pageSize, totalUsers);
  
  // 搜索处理函数
   const handleSearch = (e: React.KeyboardEvent<HTMLInputElement>) => {
     if (e.key === 'Enter') {
       // 搜索逻辑已通过useEffect自动处理
       setCurrentPage(1); // 搜索时重置到第一页
     }
   };
  
  const handleCreateUser = () => {
    setCurrentUser(null);
    setDrawerMode('create');
    setDrawerOpen(true);
  };
  
  const handleEditUser = (userId: number) => {
    const user = users.find(u => u.id === userId);
    if (user) {
      setCurrentUser(user);
      setDrawerMode('edit');
      setDrawerOpen(true);
    }
  };
  
  const handleViewUser = (userId: number) => {
    const user = users.find(u => u.id === userId);
    if (user) {
      setCurrentUser(user);
      setDrawerMode('view');
      setDrawerOpen(true);
    }
  };
  
  const handleSaveUser = async (userData: Partial<User>) => {
    try {
      if (drawerMode === 'create') {
        // 创建新用户
        const newUser = await userApi.createUser(userData);
        toast('用户创建成功');
        // 重新加载数据
        const response = await userApi.getUsers({
          page: currentPage,
          pageSize: pageSize,
          search: searchTerm,
          role: roleFilter === 'all' ? undefined : roleFilter,
          status: statusFilter === 'all' ? undefined : (statusFilter === '启用' ? 1 : 0)
        });
        setUsers(response.data);
        setTotalUsers(response.total);
      } else if (drawerMode === 'edit' && currentUser) {
        // 编辑现有用户
        await userApi.updateUser(currentUser.id, userData);
        toast('用户信息已更新');
        // 重新加载数据
        const response = await userApi.getUsers({
          page: currentPage,
          pageSize: pageSize,
          search: searchTerm,
          role: roleFilter === 'all' ? undefined : roleFilter,
          status: statusFilter === 'all' ? undefined : (statusFilter === '启用' ? 1 : 0)
        });
        setUsers(response.data);
        setTotalUsers(response.total);
      }
    } catch (error) {
      console.error('保存用户失败:', error);
      toast('保存用户失败');
    }
    setDrawerOpen(false);
  };
  
  const handleCloseDrawer = () => {
    setDrawerOpen(false);
    setCurrentUser(null);
  };
  
  const handleToggleStatus = async (userId: number, currentStatus: number) => {
    try {
      const newStatus = currentStatus === 1 ? 0 : 1; // 1-启用, 0-停用
      await userApi.toggleUserStatus(userId, newStatus);
      toast(`用户状态已${newStatus === 1 ? '启用' : '禁用'}`);
      // 重新加载数据
      const response = await userApi.getUsers({
        page: currentPage,
        pageSize: pageSize,
        search: searchTerm,
        role: roleFilter === 'all' ? undefined : roleFilter,
        status: statusFilter === 'all' ? undefined : (statusFilter === '启用' ? 1 : 0)
      });
      setUsers(response.data);
      setTotalUsers(response.total);
    } catch (error) {
      console.error('切换用户状态失败:', error);
      toast('切换用户状态失败');
    }
  };
  
  const handleAvatarChange = async (userId: number, avatar: string) => {
    try {
      await userApi.updateUser(userId, { avatar });
      // 重新加载数据
      const response = await userApi.getUsers({
        page: currentPage,
        pageSize: pageSize,
        search: searchTerm,
        role: roleFilter === 'all' ? undefined : roleFilter,
        status: statusFilter === 'all' ? undefined : (statusFilter === '启用' ? 1 : 0)
      });
      setUsers(response.data);
      setTotalUsers(response.total);
    } catch (error) {
      console.error('更新用户头像失败:', error);
      toast('更新用户头像失败');
    }
  };

  // 待审核用户操作
  const handleApproveUser = async (userId: string) => {
    try {
      const success = await approveUser(userId);
      if (success) {
        toast('用户审核通过');
        // 重新加载用户数据
        const response = await userApi.getUsers({
          page: currentPage,
          pageSize: pageSize,
          search: searchTerm,
          role: roleFilter === 'all' ? undefined : roleFilter,
          status: statusFilter === 'all' ? undefined : (statusFilter === '启用' ? 1 : 0)
        });
        setUsers(response.data);
        setTotalUsers(response.total);
      } else {
        toast('审核失败');
      }
    } catch (error) {
      console.error('审核用户失败:', error);
      toast('审核用户失败');
    }
  };

  const handleRejectUser = async (userId: string) => {
    try {
      const success = await rejectUser(userId);
      if (success) {
        toast('用户申请已拒绝');
      } else {
        toast('操作失败');
      }
    } catch (error) {
      console.error('拒绝用户失败:', error);
      toast('拒绝用户失败');
    }
  };
  
  return (
    <div>
      <div className="mb-6">
        <motion.div 
          className="mb-8"
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.5 }}
        >
        <h1 className="text-2xl font-bold text-gray-800 dark:text-gray-100">用户管理</h1>
        <p className="text-gray-600 dark:text-gray-400 mt-1">管理系统用户账号和权限</p>
        </motion.div>
      </div>
      
      {/* 选项卡 */}
      <div className="mb-6">
        <div className="border-b border-gray-200 dark:border-gray-700">
          <nav className="-mb-px flex space-x-8">
            <button
              onClick={() => setActiveTab('users')}
              className={`py-2 px-1 border-b-2 font-medium text-sm ${
                activeTab === 'users'
                  ? 'border-blue-500 text-blue-600 dark:text-blue-400'
                  : 'border-transparent text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300 hover:border-gray-300 dark:hover:border-gray-600'
              }`}
            >
              用户管理
              {users.length > 0 && (
                <span className="ml-2 bg-gray-200 dark:bg-gray-700 text-gray-800 dark:text-gray-200 text-xs px-2 py-0.5 rounded-full">
                  {users.length}
                </span>
              )}
            </button>
            <button
              onClick={() => setActiveTab('pending')}
              className={`py-2 px-1 border-b-2 font-medium text-sm ${
                activeTab === 'pending'
                  ? 'border-blue-500 text-blue-600 dark:text-blue-400'
                  : 'border-transparent text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300 hover:border-gray-300 dark:hover:border-gray-600'
              }`}
            >
              待审核用户
              {pendingUsers.length > 0 && (
                <span className="ml-2 bg-red-100 dark:bg-red-900 text-red-800 dark:text-red-200 text-xs px-2 py-0.5 rounded-full">
                  {pendingUsers.length}
                </span>
              )}
            </button>
          </nav>
        </div>
      </div>

      {/* 工具栏 */}
      <motion.div 
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.3, delay: 0.1 }}
        className="flex justify-between items-center mb-6">
        {activeTab === 'users' && (
          <div className="flex items-center space-x-4">
            <div className="relative">
              <input 
                type="text" 
                placeholder="搜索用户..." 
                className="py-2 pl-10 pr-4 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent dark:bg-gray-700 dark:text-gray-100"
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                onKeyDown={handleSearch}
              />
              <i className="fa-solid fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 dark:text-gray-500"></i>
            </div>
            
            <select 
              className="py-2 pl-3 pr-8 border border-gray-300 dark:border-gray-600 rounded-lg appearance-none focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent dark:bg-gray-700 dark:text-gray-100"
              value={statusFilter}
              onChange={(e) => setStatusFilter(e.target.value)}
            >
              <option value="all">全部状态</option>
              <option value="启用">启用</option>
              <option value="禁用">禁用</option>
            </select>
            
            <select 
              className="py-2 pl-3 pr-8 border border-gray-300 dark:border-gray-600 rounded-lg appearance-none focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent dark:bg-gray-700 dark:text-gray-100"
              value={roleFilter}
              onChange={(e) => setRoleFilter(e.target.value)}
            >
              <option value="all">全部角色</option>
              <option value="超级管理员">超级管理员</option>
              <option value="项目经理">项目经理</option>
              <option value="开发工程师">开发工程师</option>
              <option value="测试工程师">测试工程师</option>
              <option value="产品经理">产品经理</option>
            </select>
          </div>
        )}
        
        {activeTab === 'pending' && (
          <div className="text-sm text-gray-600 dark:text-gray-400">
            共有 {pendingUsers.length} 个待审核用户申请
          </div>
        )}
        
        {activeTab === 'users' && (
          <button 
            className="flex items-center bg-blue-600 hover:bg-blue-700 text-white py-2 px-4 rounded-lg transition-colors duration-300"
            onClick={handleCreateUser}
          >
            <i className="fa-solid fa-plus mr-2"></i>
            新建用户
          </button>
        )}
      </motion.div>
      
      {/* 用户列表 */}
      {activeTab === 'users' && (
        <motion.div 
          initial={{ opacity: 0, scale: 0.95 }}
          animate={{ opacity: 1, scale: 1 }}
          transition={{ duration: 0.3, delay: 0.2 }}
          className="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700 overflow-hidden">
          {loading ? (
            <div className="flex justify-center items-center py-12">
              <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
              <span className="ml-3 text-gray-600 dark:text-gray-400">加载中...</span>
            </div>
          ) : (
            <>
              <div className="overflow-x-auto">
                <table className="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
                  <thead className="bg-gray-50 dark:bg-gray-700">
                    <tr>
                      <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">头像</th>
                      <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">用户名</th>
                      <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">姓名</th>
                      <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">邮箱</th>
                      <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">角色</th>
                      <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">状态</th>
                      <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">最后登录</th>
                      <th scope="col" className="px-6 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">操作</th>
                    </tr>
                  </thead>
                  <tbody className="bg-white dark:bg-gray-800 divide-y divide-gray-200 dark:divide-gray-700">
                    {users.map((user) => (
                      <tr key={user.id} className="hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors">
                        <td className="px-6 py-4 whitespace-nowrap">
                          <Avatar user={user} onAvatarChange={handleAvatarChange} size="sm" />
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap">
                          <div className="font-medium text-gray-900 dark:text-gray-100">{user.username}</div>
                          <div className="text-xs text-gray-500 dark:text-gray-400">ID: {user.id}</div>
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-800 dark:text-gray-200">{user.name}</td>
                        <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-800 dark:text-gray-200">{user.email}</td>
                        <td className="px-6 py-4 whitespace-nowrap">
                          <RoleBadge role={user.role} />
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap">
                          <StatusBadge status={user.status} />
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-400">{user.lastLogin}</td>
                        <td className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                          <button 
                            className="text-blue-600 dark:text-blue-400 hover:text-blue-900 dark:hover:text-blue-300 mr-3"
                            onClick={() => handleViewUser(user.id)}
                          >
                            查看
                          </button>
                          <button 
                            className="text-green-600 dark:text-green-400 hover:text-green-900 dark:hover:text-green-300 mr-3"
                            onClick={() => handleEditUser(user.id)}
                          >
                            编辑
                          </button>
                          <button 
                            className={user.status === 1 ? 'text-red-600 dark:text-red-400 hover:text-red-900 dark:hover:text-red-300' : 'text-green-600 dark:text-green-400 hover:text-green-900 dark:hover:text-green-300'}
                            onClick={() => handleToggleStatus(user.id, user.status)}
                          >
                            {user.status === 1 ? '禁用' : '启用'}
                          </button>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
              
              {/* 分页组件 */}
              <div className="px-6 py-4 border-t border-gray-200 dark:border-gray-700 flex justify-between items-center">
                <div className="text-sm text-gray-500 dark:text-gray-400">显示 {startIndex} 至 {endIndex} 条，共 {totalUsers} 条</div>
                <div className="flex space-x-2">
                  <button 
                    onClick={() => setCurrentPage(prev => Math.max(prev - 1, 1))}
                    disabled={currentPage === 1}
                    className="px-3 py-1 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-700 text-gray-500 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-gray-600 disabled:opacity-50 disabled:cursor-not-allowed"
                  >
                    <i className="fa-solid fa-chevron-left text-xs"></i>
                  </button>
                  <button className="px-3 py-1 border border-blue-500 dark:border-blue-400 bg-blue-50 dark:bg-blue-900/20 text-blue-600 dark:text-blue-400 rounded-md">{currentPage}</button>
                  <button 
                    onClick={() => setCurrentPage(prev => Math.min(prev + 1, totalPages))}
                    disabled={currentPage === totalPages}
                    className="px-3 py-1 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-700 text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-600 disabled:opacity-50 disabled:cursor-not-allowed"
                  >
                    <i className="fa-solid fa-chevron-right text-xs"></i>
                  </button>
                </div>
              </div>
            </>
          )}
        </motion.div>
      )}

      {/* 待审核用户列表 */}
      {activeTab === 'pending' && (
        <motion.div 
          initial={{ opacity: 0, scale: 0.95 }}
          animate={{ opacity: 1, scale: 1 }}
          transition={{ duration: 0.3, delay: 0.2 }}
          className="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700 overflow-hidden">
          {pendingUsers.length === 0 ? (
            <div className="text-center py-12">
              <i className="fa-solid fa-user-check text-4xl text-gray-300 dark:text-gray-600 mb-4"></i>
              <p className="text-gray-500 dark:text-gray-400">暂无待审核用户</p>
            </div>
          ) : (
            <div className="overflow-x-auto">
              <table className="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
                <thead className="bg-gray-50 dark:bg-gray-700">
                  <tr>
                    <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">用户名</th>
                    <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">姓名</th>
                    <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">邮箱</th>
                    <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">注册时间</th>
                    <th scope="col" className="px-6 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">操作</th>
                  </tr>
                </thead>
                <tbody className="bg-white dark:bg-gray-800 divide-y divide-gray-200 dark:divide-gray-700">
                  {pendingUsers.map((user) => (
                    <tr key={user.id} className="hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors">
                      <td className="px-6 py-4 whitespace-nowrap">
                        <div className="font-medium text-gray-900 dark:text-gray-100">{user.username}</div>
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-800 dark:text-gray-200">{user.name}</td>
                      <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-800 dark:text-gray-200">{user.email}</td>
                      <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-400">{user.createdAt ? new Date(user.createdAt).toLocaleString('zh-CN') : '未知'}</td>
                      <td className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                        <button 
                          className="text-green-600 dark:text-green-400 hover:text-green-900 dark:hover:text-green-300 mr-3"
                          onClick={() => handleApproveUser(user.id)}
                        >
                          <i className="fa-solid fa-check mr-1"></i>
                          通过
                        </button>
                        <button 
                          className="text-red-600 dark:text-red-400 hover:text-red-900 dark:hover:text-red-300"
                          onClick={() => handleRejectUser(user.id)}
                        >
                          <i className="fa-solid fa-times mr-1"></i>
                          拒绝
                        </button>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </motion.div>
      )}

      {/* 用户管理抽屉 */}
      <UserDrawer
        isOpen={drawerOpen}
        onClose={handleCloseDrawer}
        user={currentUser}
        mode={drawerMode}
        onSave={handleSaveUser}
      />
    </div>
  );
}